<!-- 用户管理对话框 -->
<template>
    <el-dialog v-model="dialogFormVisible" title="新增管理员" width="40%">
        <el-form :model="userForm" ref="userForms" :rules="rules">
            <el-form-item prop="avatarUrl" label="头像" :label-width="formLabelWidth">
                <el-upload class="avatar-uploader" action="/api/file/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="userForm.avatarUrl" :src="userForm.avatarUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item prop="roleId" label="角色" :label-width="formLabelWidth">
                <el-select v-model="value" placeholder="请选择状态" style="width: 200px">
                    <el-option v-for="item in options" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item prop="userAccount" label="账号" :label-width="formLabelWidth">
                <el-input v-model="userForm.userAccount" />
            </el-form-item>
            <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
                <el-input v-model="userForm.password" type="password" show-password />
            </el-form-item>
            <el-form-item prop="username" label="昵称" :label-width="formLabelWidth">
                <el-input v-model="userForm.username" />
            </el-form-item>
            <el-form-item prop="userTel" label="电话" :label-width="formLabelWidth">
                <el-input v-model="userForm.userTel" />
            </el-form-item>
            <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
                <el-input v-model="userForm.email" />
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import $bus from '../../../bus'
import { AllUserRoles, UserInfo, GetAdminRoleResponseData } from '../../../api/user/type'
import { reqGetAdminRoleList, reqAddAdmin } from '../../../api/user'
import type { UploadProps } from 'element-plus'
import { ElMessage } from "element-plus"

defineProps(['paginationData'])
let userForms = ref()
let formLabelWidth = ref<String>('100px')
let dialogFormVisible = ref<Boolean>(false)
const value = ref('')
const options = reactive<AllUserRoles>([])
let $emit = defineEmits(['getAdminList'])
// 收集对话框中的数据
let userForm = reactive<UserInfo>({
    avatarUrl: '',
    userAccount: '',
    username: '',
    userTel: '',
    email: '',
    roleId: 0,
    password: ''
})

const validateUserTel = (rule: any, value: any, callback: any) => {
    let reg = /^1[3|4|5|8][0-9]\d{4,8}$/
    if (value === '') {
        callback();
    } else if (!reg.test(value)) {
        callback(new Error('手机号码格式不正确，请输入11位手机号'));
    } else {
        callback();
    }
}

// const validateRoleId = (rule: any, value: any, callback: any) => {
//     if (value === 0) {
//         callback('请选择管理员角色');
//     } else {
//         userForms.value?.clearValidate('roleId')
//         callback();
//     }
// }
const validateEmail = (rule: any, value: any, callback: any) => {
    let reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.\w{2,}$/
    if (value === '') {
        callback();
    } else if (!reg.test(value)) {
        callback(new Error('邮箱格式不正确'));
    } else {
        callback();
    }
}
// 表单校验
const rules = {
    avatarUrl: [
        { required: true, message: '头像不能为空', trigger: 'change' }
    ],
    userAccount: [
        { required: true, message: '账号不能为空', trigger: 'blur' },
        { min: 5, max: 20, message: '账号长度应该为5-20位之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 6, max: 12, message: '密码长度应在6-12位之间', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '昵称不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '昵称长度应在2-10位之间', trigger: 'blur' }
    ],
    roleId: [
        { required: true, trigger: 'blur' }
    ],
    userTel: [{ validator: validateUserTel, trigger: 'change' }],
    email: [{ validator: validateEmail, trigger: 'change' }]
}

onMounted(() => {
    $bus.on('add', async (obj: any) => {
        userForm.roleId = 0
        userForm.avatarUrl = ''
        userForm.userAccount = ''
        userForm.password = ''
        userForm.username = ''
        userForm.userTel = ''
        userForm.email = ''
        value.value = ''

        // 显示对话框
        dialogFormVisible.value = obj
        let result: GetAdminRoleResponseData = await reqGetAdminRoleList()
        if (result.code == 20000) {
            Object.assign(options, result.data)
        }
        // 清除表单校验结果
        // userForms.value?.clearValidate('avatarUrl')
        // userForms.value?.clearValidate('userAccount')
        // userForms.value?.clearValidate('password')
        // userForms.value?.clearValidate('username')
        // userForms.value?.clearValidate('roleId')
        userForms.value?.resetFields()
    })
})


// 对话框确认按钮回调
const submit = async () => {
    await userForms.value.validate();
    userForm.roleId = value.value

    if (userForm.roleId == 0) {
        ElMessage.warning('请选择管理员绝色')
        return
    } else {
        let result = await reqAddAdmin(userForm)
        if (result.code == 20000) {
            $emit('getAdminList')
            ElMessage.success('管理员新增成功')
            // 关闭对话框
            dialogFormVisible.value = false
        } else {
            ElMessage.error('管理员新增失败')
            // 关闭对话框
            dialogFormVisible.value = false
        }

    }
}

// 图片上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    userForm.avatarUrl = response.data.url
    userForms.value.clearValidate('avatarUrl')
}
// 图片上传之前触发的钩子 可以限制上传的格式 大小 文件类型
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif ') {
        if (rawFile.size / 1024 / 1024 < 2) {
            return true
        } else {
            ElMessage.error('上传图片的大小不能超过 2MB!')
            return false
        }

    } else {
        ElMessage.error('上传文件的格式必须是 jpeg / png / gif')
        return false
    }
}

</script>

<style lang="scss" scoped>
.el-form {
    padding-right: 50px;
    padding-top: 20px;

    .avatar-uploader {

        .avatar {
            width: 110px;
            height: 110px;
        }
    }

}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 110px;
    text-align: center;
}
</style>